package com.watson.thread;

import java.util.List;
import java.util.Set;
import java.util.concurrent.RecursiveTask;

/**
 * @program: mytest
 * @description: fork join poll
 * @author: zhangpeng348@jd.com
 * @date: 2018-12-13 15:41
 **/
public class MergeSet extends RecursiveTask<Set<String>> {

    private List<Set<String>> setList;
    private int size;


    public MergeSet(List<Set<String>> setList, int size) {
        this.setList = setList;
        this.size = size;
    }

    @Override
    protected Set<String> compute() {
        if (this.size == 2) {
            setList.get(0).addAll(setList.get(1));
            return setList.get(0);
        } else if (this.size == 1) {
            return setList.get(0);
        } else if (this.size > 2) {
            int mid = this.size/2;
            MergeSet left = new MergeSet(setList.subList(0, mid), mid);
            MergeSet right = new MergeSet(setList.subList(mid + 1, this.size), this.size - mid);
            left.fork();
            right.fork();
            left.join().addAll(right.join());
            return left.join();
        }
        return null;
    }
}
